package com.wzh.ojcodesandbox.codesandbox.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.wzh.ojcodesandbox.codesandbox.CodeSandbox;
import com.wzh.ojcodesandbox.model.ExecuteCodeRequest;
import com.wzh.ojcodesandbox.model.ExecuteCodeResponse;
import com.wzh.ojcodesandbox.model.ExecuteMessage;
import com.wzh.ojcodesandbox.model.entity.JudgeInfo;
import com.wzh.ojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author wzh
 * 代码沙箱模板方法的实现
 */
@Slf4j
public abstract class JavaCodeSandboxTemplate implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final long TIME_OUT = 5000L;


    @Resource
    private ThreadPoolTaskExecutor executor;


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        String code = executeCodeRequest.getCode();
        List<String> inputs = executeCodeRequest.getInputList();
//        1.将用户的代码保存为文件
        File file = saveCodeToFile(code);
//        2.编译
        ExecuteMessage executeMessage = compileFile(file);
//        3.运行
        List<ExecuteMessage> executeMessages = null;
        try {
            executeMessages = runFile(file, inputs);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
//        4.收集整理输出
        ExecuteCodeResponse outputResponse = getOutputResponse(executeMessages);
//        5.文件清理
/*        boolean b = deleteFile(file);

        if (!b){
            log.error("deleteFile error, userCodeFilePath = {}", file.getAbsolutePath());
        }*/
        return outputResponse;
    }

    /**
     * 将用户代码保存为文件
     *
     * @param code 用户代码
     * @return 文件
     */
    public File saveCodeToFile(String code) {
        String userDir = System.getProperty("user.dir");

        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;

        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath +File.separator+ GLOBAL_JAVA_CLASS_NAME;
        return FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
    }


    /**
     * 编译用户代码
     *
     * @param userCodeFile 用户代码文件
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile) {
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            if (executeMessage.getExitValue() != 0) {
                throw new RuntimeException("编译错误");
            }
            return executeMessage;
        } catch (Exception e) {
//            return getErrorResponse(e);
            throw new RuntimeException(e);
        }
    }


    /**
     * 运行程序
     *
     * @param userCodeFile
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) throws ExecutionException, InterruptedException {
        Future<List<ExecuteMessage>> res = executor.submit(new Callable<List<ExecuteMessage>>() {
            @Override
            public List<ExecuteMessage> call() throws Exception {
                String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
                List<ExecuteMessage> executeMessageList = new ArrayList<>();
                for (String inputArgs : inputList) {
                    String execCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
                    try {
                        Process execProcess = Runtime.getRuntime().exec(execCmd);
                        // 超时控制
                        new Thread(() -> {
                            try {
                                Thread.sleep(TIME_OUT);
                                System.out.println("超时了，中断");
                                execProcess.destroy();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }).start();
                        ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(execProcess, "运行");
                        executeMessageList.add(executeMessage);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                }
                return executeMessageList;
            }
        });

        return res.get();
    }

    /**
     * 获取输出结果
     *
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 取用时最大值，便于判断是否超时
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        // 正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        // 要借助第三方库来获取内存占用，非常麻烦，此处不做实现
//      　　　　  judgeInfo.setMemory();
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    /**
     * 5、删除文件
     *
     * @param userCodeFile
     * @return
     */
    public boolean deleteFile(File userCodeFile) {
        if (userCodeFile.getParentFile() != null) {
            String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }

    /**
     * 6、获取错误响应
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
